﻿/// -----------------------------------------------------------------------
/// (c) 2009 Microsoft Corporation -- All rights reserved
/// This code is licensed under the MS-PL
/// http://www.opensource.org/licenses/ms-pl.html
/// Courtesy of the Open Source Techology Center: http://port25.technet.com
/// -----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.XPath;
using System.Xml;
using System.Text.RegularExpressions;

namespace mkProject
{
    public class CommandLine
    {
        static string EVIL_SPACE_CHAR = new string((char)254, 1);
        static string EVIL_QUOTE_CHAR = new string((char)253, 1);

        public static string UnMuckString(string s) {
            return s.Replace(EVIL_SPACE_CHAR, " ").Replace(EVIL_QUOTE_CHAR, @"\""");
        }

        public string cmd;
        public List<string> parameters = new List<string>();
        public List<string> switches = new List<string>();
        public CommandLine(string commandLine) {
            cmd = commandLine;

            // clean up switches that have a space between the switch and parameter
            
            cmd = Regex.Replace(cmd, "\\s([/-][DdIi])\\s*", " $1");
            cmd = Regex.Replace(cmd, "\\s([/-]Fo)\\s*", " $1");
            
            cmd = cmd.Replace(@"\""", EVIL_QUOTE_CHAR);

           // if (cmd.IndexOf("ate/lib") > 0)
           //     cmd = cmd + "";

            // Muck-up-string.
            // switch out quoted sets with unquoted ones, sub'ing in char 240 for space.
            Regex regEx = new Regex(@""".*?""", RegexOptions.IgnoreCase);
            MatchCollection matches = regEx.Matches(cmd);
            foreach (Match item in matches) {
                string m = item.Captures[0].Value;
                string n = m.Replace(" ", EVIL_SPACE_CHAR).Replace(@"""", ""); // replace spaces with an odd char , and eliminate quotes.
                cmd = cmd.Replace(m, n);
            }
            
            // grab all the command line switches. 
            regEx = new Regex(@"[/-]([^/\s\-]\S*)", RegexOptions.IgnoreCase);
            matches = regEx.Matches(cmd);

            foreach (Match item in matches) {
                switches.Add(UnMuckString(item.Captures[0].Value.Trim()));
            }

            regEx = new Regex(@"\s+([^/\-]\S*)", RegexOptions.IgnoreCase);
            matches = regEx.Matches(cmd);

            foreach (Match item in matches) {
                parameters.Add(UnMuckString(item.Captures[0].Value.Trim()));
            }

        }
    }
}
